package Engine;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;

public class Repositorio {

    public void createFile(String text) throws IOException {
        java.io.File diretorio = new java.io.File("C:\\Cubesoft");
        diretorio.mkdir();
        java.io.File arquivo = new java.io.File(diretorio, "EPF.cpr");
        try {
            arquivo.createNewFile();
        } catch (IOException e) {
            JOptionPane.showMessageDialog(null, "Erro: " + e);
        }
        FileWriter fileWriter = new FileWriter(arquivo, false);
        try (PrintWriter printWriter = new PrintWriter(fileWriter)) {
            printWriter.println(text);
            printWriter.flush();
        }
    }

    public String getFileChooser() {
        JFileChooser chooser = new JFileChooser();        
        chooser.setDialogTitle("Abrir Arquivo");
        chooser.setDialogType(JFileChooser.OPEN_DIALOG);        
        FileFilter filter = new FileNameExtensionFilter("CPR", new String[]{"cpr"});
        chooser.setFileFilter(filter);        
        File file = new File("C:\\");
        chooser.setCurrentDirectory(file);
        int retorno = chooser.showOpenDialog(null);
        if (retorno == JFileChooser.APPROVE_OPTION) {
            return chooser.getSelectedFile().getAbsolutePath();
        }
        return null;
    }

    public String readFile(String file) {        
        try {
            BufferedReader bufferedReader;
            try (FileReader fileReader = new FileReader(file)) {
                bufferedReader = new BufferedReader(fileReader);
                String linha;
                while ((linha = bufferedReader.readLine()) != null) {
                    return (linha);
                }
            }
            bufferedReader.close();
        } catch (IOException e) {
            JOptionPane.showMessageDialog(null, "Erro: " + e);
        }
        return null;
    }
}
